<?php

namespace app\controller;

use app\general\utils\ConversionUtils;
use app\model\BasicGenre;
use Carbon\Carbon;
use support\Db;
use support\Request;

class GenreController extends BaseController
{
    public function index(Request $request)
    {
        $query = Db::table('basic_genre')
            ->when($request->input('name'), function ($query) use ($request) {
                return $query->where('name', 'like', '%'.$request->input('dictName').'%');
            })
           ->paginate($request->get('pageSize'));
        $items = $query->items();
        foreach ($items as $key=>$val){
            $items[$key] = ConversionUtils::underscoreToHump($val) ;
            $items[$key]['createTime'] = Carbon::parse($items[$key]['createTime'])->toIso8601String();
        }
        return  json($this->success('操作成功',$items,$query->total()));
    }

    /**
     * 创建
     * @param Request $request
     * @return \support\Response
     */
    public function store(Request $request)
    {
        $BasicGenre = new BasicGenre();
        $BasicGenre->setRawAttributes(ConversionUtils::humpToUnderscore($request->all()));
        $BasicGenre->version=0;
        $BasicGenre->save();
        return  json($this->success('操作成功'));
    }

    /**
     * 更新
     * @param Request $request
     * @param $id
     * @return \support\Response
     */
    public function update(Request $request,$id)
    {
        $BasicGenre = BasicGenre::find($id);
        if(empty($BasicGenre)){
            return  json($this->success('操作失败'));
        }
        $data = $request->all();
        $data = ConversionUtils::humpToUnderscore($data);
        unset($data['create_time'],$data['updateTime']);
        $BasicGenre->setRawAttributes($data);
        $BasicGenre->save();
        return  json($this->success('操作成功'));
    }

    /**
     * 删除
     * @param Request $request
     * @param $id
     * @return \support\Response
     */
    public function destroy(Request $request, $id)
    {
        BasicGenre::destroy($id);
        return  json($this->success('操作成功'));
    }

    public function getAll(Request $request)
    {
        $query = Db::table('basic_genre')
            ->when($request->input('columnValue'), function ($query) use ($request) {
                return $query->where('column_value', $request->input('columnValue'));
            })->get();
        $items = empty($query)?[]:$query->toArray();


        foreach ($items as $key=>$val){
            $items[$key] = ConversionUtils::underscoreToHump($val) ;
            $items[$key]['createTime'] = Carbon::parse($items[$key]['createTime'])->toIso8601String();
        }
        return  json($this->successData('操作成功',$items));
    }

}
